package com.dyit.springcloud.common.config.mvc;

import lombok.SneakyThrows;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.convert.converter.Converter;
import org.springframework.format.FormatterRegistry;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.text.SimpleDateFormat;
import java.util.Date;

@Configuration
public class CommonMvcConfig implements WebMvcConfigurer {

    private final static ThreadLocal<SimpleDateFormat> LOCAL=new ThreadLocal<>();//控制线程安全
    private final static SimpleDateFormat sdf=new SimpleDateFormat();

    @Override
    public void addFormatters(FormatterRegistry registry) {
        registry.addConverter(new Converter<String, Date>() {
            @Override
            @SneakyThrows
            public Date convert(String s) {
                if(LOCAL==null){
                    LOCAL.set(sdf);
                }
                SimpleDateFormat simpleDateFormat = LOCAL.get();
                Date date = simpleDateFormat.parse(s);
                return date;
            }
        });
    }

    /**
     * 解决跨域问题
     * @param registry
     */
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowCredentials(true)
                .allowedMethods("Get","Post","Put","Delete")
                .maxAge(60*60);
    }
}
